define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {

    var sysPath = getServer() + "/static/app/fxpg/fxEconomicLossProbabilityCompute";

    var fxEconomyLossProbabilityComputeFormHtml = sysPath + "/views/fxEconomicLossProbabilityComputeForm.html";
    var getFxEconomyLossProbabilityComputeController = function () {
        return getServer() + "/fxEconomyLossProbabilityComputes";
    };
    var getFxBuildingsController = function () {
        return getServer() + "/fxBuildingss";
    };
    var getFxVulnerabilityProvinceController = function () {
        return getServer() + "/fx/fxVulnerabilityProvinces";
    };
    var getFxDamagePercentController = function () {
        return getServer() + "/fxDamagePercents";
    };
    var getFxEconomicLossController = function () {
        return getServer() + "/fxEconomicLosss";
    };
    var getFxVulnerabilityDangerController = function () {
        return getServer() + "/fxVulnerabilityDangers";
    };

    /**
     * 页面初始化
     */
    var buildingDamagePercent, buildingResetUnitPrice, vulnerabilityDanger, vulnerabilityProvince,
        probabilityVulnerability;
    var global_K0 = 0, global_K1 = 0;
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("北京市", "北京市", "海淀区");
    };
    var initProvinceSelect = function (Province, City, Area) {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        //debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(Area);
                                    // 列表
                                    mainMethod();
                                    //createFxEconomyLossProbabilityComputeGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(Province);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            mainMethod();
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("北京市", "北京市", "海淀区");
        });
    };
    var mainMethod = function () {
        if (!buildingDamagePercent || !buildingResetUnitPrice || !vulnerabilityDanger || !vulnerabilityProvince) {
            queryFxDamagePercents();
            queryFxResetUnitPrice();
            queryFxVulnerabilityDanger();
            queryFxVulnerabilityProvince();
            var t = setInterval(function () {
                if (buildingDamagePercent && buildingResetUnitPrice && vulnerabilityDanger && vulnerabilityProvince) {
                    clearInterval(t);
                    var sType, temp_obj = {};
                    for (let i = 0; i < buildingDamagePercent.length; i++) {
                        sType = buildingDamagePercent[i].structureType;
                        temp_obj[sType] = {
                            "0": parseFloat(buildingDamagePercent[i].intact),
                            "1": parseFloat(buildingDamagePercent[i].slight),
                            "2": parseFloat(buildingDamagePercent[i].medium),
                            "3": parseFloat(buildingDamagePercent[i].serious),
                            "4": parseFloat(buildingDamagePercent[i].whole)
                        };
                    }
                    buildingDamagePercent = temp_obj;
                    console.log("damagePercent: ", buildingDamagePercent);
                    temp_obj = {};
                    for (let i = 0; i < buildingResetUnitPrice.length; i++) {
                        sType = buildingResetUnitPrice[i].structureType;
                        temp_obj[sType] = parseFloat(buildingResetUnitPrice[i].price);
                    }
                    buildingResetUnitPrice = temp_obj;
                    console.log("resetUnitPrice: ", buildingResetUnitPrice);
                    temp_obj = {}
                    var viVal = 0, viiVal = 0, viiiVal = 0, ixVal = 0, xVal = 0, vd;
                    for (let i = 0; i < vulnerabilityDanger.length; i++) {
                        vd = vulnerabilityDanger[i];
                        viVal = vd.viEarthquakeIntensity;
                        viiVal = vd.viiEarthquakeIntensity;
                        viiiVal = vd.viiiEarthquakeIntensity;
                        ixVal = vd.ixEarthquakeIntensity, xVal = vd.xearthquakeIntensity;
                        temp_obj[vulnerabilityDanger[i].area] = [parseFloat(viVal), parseFloat(viiVal), parseFloat(viiiVal), parseFloat(ixVal), parseFloat(xVal)];
                    }
                    vulnerabilityDanger = temp_obj;
                    console.log("vulnerabilityDanger: ", vulnerabilityDanger);

                    temp_obj = {};
                    //console.log(vulnerabilityProvince);
                    for (let i = 0; i < vulnerabilityProvince.length; i++) {
                        var vp = vulnerabilityProvince[i];
                        sType = vp.structureType;
                        !temp_obj[vp.area] && (temp_obj[vp.area] = {});
                        !temp_obj[vp.area][sType] && (temp_obj[vp.area][sType] = {});
                        temp_obj[vp.area][sType][vp.damageDegree] = [parseFloat(vp.vulnerabilityVI), parseFloat(vp.vulnerabilityVII), parseFloat(vp.vulnerabilityVIII), parseFloat(vp.vulnerabilityIX), parseFloat(vp.vulnerabilityX)];
                    }
                    vulnerabilityProvince = temp_obj;
                    console.log("vulnerabilityProvince: ", vulnerabilityProvince);

                    computeInnerProductByIntensity();
                    console.log("probabilityVulnerability: ", probabilityVulnerability);

                    fxEconomyLossProbabilityComputeByArea();
                } else {
                }
            }, 100);
        } else if (buildingDamagePercent && buildingResetUnitPrice && vulnerabilityDanger && vulnerabilityProvince) {
            console.log("-------damagePercent: ", buildingDamagePercent);
            console.log("-------resetUnitPrice: ", buildingResetUnitPrice);
            console.log("-------vulnerabilityDanger: ", vulnerabilityDanger);
            console.log("-------vulnerabilityProvince: ", vulnerabilityProvince);
            console.log("-------probabilityVulnerability: ", probabilityVulnerability);
            fxEconomyLossProbabilityComputeByArea();
        }
    };
    var queryFxDamagePercents = function () {
        $.ajax({
            url: getFxDamagePercentController() + "/getFxDamagePercents",
            type: "get",
            success: function (result) {
                buildingDamagePercent = result;
            }
        });
    };
    var queryFxResetUnitPrice = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxEconomicLossController() + "/listFxEconomicLosss?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (result) {
                buildingResetUnitPrice = result;
            }
        });
    }
    var queryFxVulnerabilityDanger = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxVulnerabilityDangerController() + "/getFxVulnerabilityDangers?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (result) {
                vulnerabilityDanger = result;
            }
        });
    }
    var queryFxVulnerabilityProvince = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxVulnerabilityProvinceController() + "/findFxVulnerabilityProvinces?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (result) {
                vulnerabilityProvince = result;
            }
        });
    }
    var computeInnerProductByIntensity = function () {
        probabilityVulnerability = {};
        for (const area in vulnerabilityProvince) {
            var type2Vuls = vulnerabilityProvince[area], probabilities = vulnerabilityDanger[area];
            probabilityVulnerability[area] = {};
            for (const sType in type2Vuls) {
                probabilityVulnerability[area][sType] = {};
                var dg2vul = type2Vuls[sType]
                for (const dg in dg2vul) {
                    var vuls = dg2vul[dg], sum = 0;
                    for (let i = 0; i < vuls.length; i++) {
                        sum += vuls[i] * probabilities[i];
                    }
                    //sum > 2 ? (sum -= 2) : ((sum > 1) ? (sum -= 1) : sum);//仅用于测试
                    probabilityVulnerability[area][sType][dg] = sum;
                }
            }
        }
    };

    var computeK = function (dataStore) {
        var pointX = [], pointY = [], type2point = {};
        for (const area in probabilityVulnerability) {

            var type2Vuls = probabilityVulnerability[area];
            for (const sType in type2Vuls) {
                type2point[sType] = {};
                pointX = [];
                pointY = [];
                var dg2vul = type2Vuls[sType];
                for (const dg in dg2vul) {
                    pointX.push(Math.log(dataStore["data"][dg] == 0 ? 0.00000000000000000001 : dataStore["data"][dg]));
                    pointY.push(Math.log(dg2vul[dg]));
                    //pointX.push((dataStore["data"][dg] == 0 ? 0.0000000000000001 : dataStore["data"][dg]));
                    //pointY.push((dg2vul[dg]));
                }
                type2point[sType]['X'] = pointX;
                type2point[sType]['Y'] = pointY;
            }
        }
        console.log("type2point: ", type2point);
        var ys = [0.01, 0.001, 0.00001, 0.000001], y2x = {}, x = 0, y = 0, temp_str = "";
        var type2xy = {};
        for (const sType in type2point) {
            pointX = type2point[sType]["X"].slice(1);//slice仅用于测试
            pointY = type2point[sType]["Y"].slice(1);
            console.log(pointX);
            var res = reckonK(pointX, pointY);
            var p1 = res["p1"], p2 = res["p2"];
            console.log("r: ", res["r"], "p1: ", p1, " p2: ", p2);
            var K0 = Math.pow(Math.E, p2), K1 = -p1;
            console.log(sType, "K0: ", K0, " K1: ", K1);

            //var y = K0 * Math.pow(x, -K1);
            //lnx=(lnk0-lny)/k1 x=Math.pow(Math.E, (lnk0-lny)/k1)
            var XS = [], YS = [];
            for (let i = 0; i < ys.length; i++) {
                y = Math.log(ys[i]);
                //x = Math.pow(Math.E, (Math.log(K0 / y)) / K1);
                var v = (Math.log(K0) - y) / K1;
                x = Math.pow(Math.E, v);
                XS.push(x);
                YS.push(ys[i]);
                console.log(ys[i], x);
            }
            type2xy[sType] = {"X": XS, "Y": YS};
            //break;

        }
        console.log(type2xy);
        var pointXS = [];
        for (const sType in type2xy) {
            pointX = type2xy[sType]["X"];
            pointXS.push(pointX);
        }
        var len = pointXS.length > 0 ? pointXS[0].length : 0, sumPXS = [];
        for (let j = 0; j < len; j++) {
            var sumPX = 0;
            for (let i = 0; i < pointXS.length; i++) {
                sumPX += pointXS[i][j];
            }
            sumPX = sumPX / len;
            sumPX = Math.log(sumPX);
            sumPXS.push(sumPX);
        }
        //sumPXS = sumPXS.slice(1);//slice仅用于测试
        for (let i = 0; i < ys.length; i++) {
            ys[i] = Math.log(ys[i]);
        }
        console.log("sumPXS: ", sumPXS, "ys: ", ys);
        var res = reckonK(sumPXS, ys);
        var p1 = res["p1"], p2 = res["p2"];
        console.log("rr: ", res["r"], "pp1: ", p1, " pp2: ", p2);
        var K0 = Math.pow(Math.E, p2), K1 = -p1;
        console.log("KK0: ", K0, " KK1: ", K1);

        global_K0 = K0;
        global_K1 = K1;
        /*
        var yy = 0.01; yy = Math.log(yy);
        var v = (Math.log(K0) - yy) / K1;
        var xx = Math.pow(Math.E, v);
        console.log("xx: ", xx, " yy: ", yy);*/
    };
    var reckonK = function (X, Y) {
        var res = {};
        var len = X.length;
        var x = new Array(len), y = new Array(len);
        var sumX = 0.0, sumY = 0.0, sumX2 = 0.0;
        for (let n = 0; n < len; n++) {
            x[n] = X[n];
            y[n] = Y[n];
            sumX += x[n];
            sumX2 += x[n] * x[n];
            sumY += y[n];
        }
        var meanX = sumX / len, meanY = sumY / len;

        var xxbar = 0.0, yybar = 0.0, xybar = 0.0;
        for (var i = 0; i < len; i++) {
            xxbar += (x[i] - meanX) * (x[i] - meanX);
            yybar += (y[i] - meanY) * (y[i] - meanY);
            xybar += (x[i] - meanX) * (y[i] - meanY);
        }
        var beta1 = xybar / xxbar;
        var beta0 = meanY - beta1 * meanX;

        var df = len - 2;
        var rss = 0.0;
        var ssr = 0.0;
        for (var i = 0; i < len; i++) {
            var fit = beta1 * x[i] + beta0;
            rss += (fit - y[i]) * (fit - y[i]);
            ssr += (fit - meanY) * (fit - meanY);
            //ssr += (y[i] - meanY) * (y[i] - meanY);
        }
        //var r_2 = 1 - rss / ssr;
        //console.log("r_2: ", r_2);
        var R2 = ssr / yybar;
        res["r"] = R2;
        res["p1"] = beta1;
        res["p2"] = beta0;
        return res;
    }

    var fxEconomyLossProbabilityComputeByArea = function () {
        //type2point = {};
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "",
            area = $("#areaSelect").val() || "";
        $.ajax({
            url: getFxBuildingsController() + "/getFxBuildingss?province=" + province + "&city=" + city + "&area=" + area,
            type: "get",
            success: function (data) {
                console.log(data);
                if (data && data.length > 0) {
                    var dataStore = {"province": province, "city": city, "area": area, "data": {}};
                    for (let i = 0; i < data.length; i++) {
                        var type2Vuls = probabilityVulnerability[data[i].area],
                            dg2vul = type2Vuls[data[i].structureType], vul = 0, loss = 0;
                        var bDamagePercent = 0, bResetUnitPrice = buildingResetUnitPrice[data[i].structureType];
                        for (const damageDegree in dg2vul) {
                            vul = dg2vul[damageDegree];
                            bDamagePercent = buildingDamagePercent[data[i].structureType][damageDegree] * 0.01;
                            loss = data[i].buildingArea * vul * bDamagePercent * bResetUnitPrice;
                            !dataStore["data"][damageDegree] ? (dataStore["data"][damageDegree] = loss) : (dataStore["data"][damageDegree] += loss);
                        }
                        //console.log("dataStore: ", dataStore);
                    }
                    console.log("dataStore: ", dataStore);
                    updateEconomicLossProbabilityCompute(dataStore);
                    computeK(dataStore);
                } else {
                    $('#fxEconomyLossProbabilityComputeGrid').datagrid('loadData', {total: 0, rows: []});
                    $('#fxEconomyLossProbabilityComputeGrid').datagrid('appendRow', {});
                    var body = $("#fxEconomyLossProbabilityComputeGrid").data().datagrid.dc.body2;
                    var trs = body.find('table tbody').find("tr");
                    while (trs.eq(0).find("td").length > 1) {
                        if (trs.eq(0).find("td").length == 1) break;
                        trs.eq(0).find("td").eq(1).remove();
                    }
                    trs.eq(0).find("td").eq(0).attr("colspan", 6).attr("width", body.width()).css("text-align", "center").html("查询无数据");
                }
            }
        });
    };
    var updateEconomicLossProbabilityCompute = function (dataStore) {
        var p = dataStore.province, c = dataStore.city, a = dataStore.area, buildingIsFinished = {};
        var _dataStore = dataStore["data"];
        console.log("=========", dataStore);
        $.ajax({
            url: getFxEconomyLossProbabilityComputeController() + "/getFxEconomyLossProbabilityComputes?province=" + p + "&city=" + c + "&area=" + a,
            contentType: "application/json",
            type: "GET",
            success: function (elpc) {
                console.log("elpc: ", elpc);
                if (elpc && elpc.length) {
                    var dg = "", _expectation = 0;
                    for (let idx = 0; idx < elpc.length; idx++) {
                        dg = elpc[idx].damageDegree;
                        _expectation += (elpc[idx].correctedProbability ? elpc[idx].correctedProbability : 0) * parseFloat(_dataStore[dg]);
                    }
                    //console.log("_expectation: ", _expectation);
                    for (let damageDegree in _dataStore) {
                        buildingIsFinished[damageDegree] = false;
                        $.ajax({
                            url: getFxEconomyLossProbabilityComputeController() + "/getFxEconomyLossProbabilityComputes?province=" + p + "&city=" + c + "&area=" + a + "&damageDegree=" + damageDegree,
                            contentType: "application/json",
                            type: "GET",
                            success: function (_data) {
                                //console.log(tt++, _key, damageDegree);
                                //console.log(_data);
                                if (_data && _data.length == 1) {
                                    var _result = _data[0];
                                    _result.economicLoss = parseFloat(_dataStore[damageDegree].toFixed(4));
                                    _result.expectation = _expectation.toFixed(5);
                                    //console.log(dataStore[_key][damageDegree], "-----" ,_result.calculatedValue);
                                    $.ajax({
                                        url: getFxEconomyLossProbabilityComputeController(),
                                        contentType: "application/json",
                                        data: JSON.stringify(_result),
                                        type: "put",
                                        success: function (__data) {
                                            console.log(__data.message);
                                            if (__data.message == "计算出现错误!") Util.alert(p + c + a + '-' + '-' + damageDegree + ': 计算出现错误!');
                                            buildingIsFinished[damageDegree] = true;
                                            taskIsFinish(buildingIsFinished) && (createFxEconomyLossProbabilityComputeGrid(), Util.alert("计算完成!"));
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            }
        });
    };
    var createFxEconomyLossProbabilityComputeGrid = function () {
        $("#fxEconomyLossProbabilityComputeGrid").datagrid({
            url: getFxEconomyLossProbabilityComputeController() + "/getFxEconomyLossProbabilityComputes",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {
                    field: 'province',
                    title: '省',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    width: '10%',
                    align: 'center',
                    formatter: function (value) {
                        //console.log(arguments[1]);
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
                },
                {
                    field: 'fitedProbability',
                    title: '拟合概率计算值(p)',
                    width: '10%',
                    align: 'center',
                    editor: {type: 'numberbox', options: {precision: 5}},
                },
                {
                    field: 'correctedProbability',
                    title: '概率-修正值',
                    width: '10%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        var correctedProbability = new Number(value).toFixed(2);
                        return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\', \'correctedProbability\');"> ' + correctedProbability + ' </a> '
                    }
                },
                {
                    field: 'economicLoss',
                    title: '经济损失-计算（万元）',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'expectation',
                    title: '期望',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'correctedExpectation',
                    title: '期望-修正值',
                    width: '10%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        var correctedExpectation = new Number(value).toFixed(2);
                        return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\', \'correctedExpectation\');"> ' + correctedExpectation + ' </a> '
                    }
                },
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxEconomyLossProbabilityCompute();
                }
            },*/ {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    exportFxEconomyLossProbabilityComputeTemplet();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importFxEconomyLossProbabilityCompute();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportFxEconomyLossProbabilityCompute();
                }
            }/*, {
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxEconomyLossProbabilityCompute();
                }
            }*/],
            queryParams: {
                province: $("#provinceSelect").val(),
                city: $("#citySelect").val(),
                area: $("#areaSelect").val(),
            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxEconomyLossProbabilityComputeGrid", "province,city,area,expectation,correctedExpectation");
            },
            onClickCell: function (rowIndex, field, value) {
                //console.log("onClickCell: ", rowIndex, field, value);
                if (field == "fitedProbability") {
                    global_editedCell && $(global_editedCell["this"]).datagrid('endEdit', global_editedCell["rowIndex"]);
                    $(this).datagrid('beginEdit', rowIndex);
                    global_editedCell = {"this": this, "rowIndex": rowIndex};
                } else {
                    console.log('endEdit',);
                    global_editedCell && $(global_editedCell["this"]).datagrid('endEdit', global_editedCell["rowIndex"]);
                }
            },
            onAfterEdit: function (index, row, changes) {
                console.log("onAfterEdit: ", index, row, changes);
                var fp = changes.fitedProbability, yy = parseFloat(fp);
                yy = Math.log(yy);
                var v = (Math.log(global_K0) - yy) / global_K1;
                var xx = Math.pow(Math.E, v);
                console.log("xx: ", xx, " yy: ", yy);
                $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[index]["fitedProbability"] = fp;
                $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[index]["economicLoss"] = xx.toFixed(4);

                var rowsData = $("#fxEconomyLossProbabilityComputeGrid").datagrid('getData').rows,
                    economicLossExpectation = 0;
                for (let i = 0; i < rowsData.length; i++) {
                    economicLossExpectation += rowsData[i].correctedProbability * rowsData[i].economicLoss;
                }
                //console.log("economicLossExpectation: ", economicLossExpectation);
                for (let i = 0; i < rowsData.length; i++) {
                    $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[i]["expectation"] = economicLossExpectation.toFixed(4);
                    $("#fxEconomyLossProbabilityComputeGrid").datagrid('refreshRow', i);
                }
                mergeCells("fxEconomyLossProbabilityComputeGrid", "province,city,area,expectation,correctedExpectation");
            },
            /*pagination: true,
            pageSize: 10*/
        });
    };
    var global_editedCell;
    $.extend($.fn.datagrid.defaults.editors, {
        text: {
            init: function (container, options) {
                var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
                return input;
            },
            getValue: function (target) {
                return $(target).val();
            },
            setValue: function (target, value) {
                $(target).val(value);
            },
            resize: function (target, width) {
                var input = $(target);
                if ($.boxModel == true) {
                    input.width(width - (input.outerWidth() - input.width()));
                } else {
                    input.width(width);
                }
            }
        }
    });

    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };
    var formValidator = function () {
        $("#fxEconomyLossProbabilityComputeForm").validate({
            rules: {
                fitedProbability: {
                    required: true,
                },
                correctedProbability: {
                    required: true,
                },
            },
            messages: {
                fitedProbability: {
                    required: "拟合概率计算值(p)不允许为空!",
                },
                correctedProbability: {
                    required: "概率-修正值不允许为空!",
                },
            }
        });
    };
    var getFxEconomyLossProbabilityCompute = function (id) {
        $.ajax({
            url: getFxEconomyLossProbabilityComputeController() + "/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("fxEconomicLossProbabilityComputeForm", data);
            }
        });
    };

    var addFxEconomyLossProbabilityCompute = function () {
        var slidebar = Util.slidebar({
            url: fxEconomyLossProbabilityComputeFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxEconomyLossProbabilityComputeForm").valid()) {
                        var data = Tool.serialize("fxEconomicLossProbabilityComputeForm");
                        $.ajax({
                            url: getFxEconomyLossProbabilityComputeController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxEconomyLossProbabilityComputeGrid();
                            }
                        });
                    }
                });
            }
        });
    };

    window._editFxEconomyLossProbabilityCompute = function (fxEconomyLossProbabilityComputeId, field) {
        var slidebar = Util.slidebar({
            url: fxEconomyLossProbabilityComputeFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                assistProbabilityCompute(field);
                formValidator();
                getFxEconomyLossProbabilityCompute(fxEconomyLossProbabilityComputeId);
                if (field == "correctedProbability") {
                    $("#saveBtn").on("click", function () {
                        if ($("#fxEconomicLossProbabilityComputeForm").valid()) {
                            var data = Tool.serialize("fxEconomicLossProbabilityComputeForm");
                            $.ajax({
                                url: getFxEconomyLossProbabilityComputeController(),
                                contentType: "application/json",
                                data: JSON.stringify(data),
                                type: "put",
                                success: function (data) {
                                    Util.alert(data.message);
                                    slidebar.close();
                                    createFxEconomyLossProbabilityComputeGrid();
                                }
                            });
                        }
                    });
                } else if (field == "correctedExpectation") {
                    $("#saveBtn").on("click", function () {
                        if ($("#fxEconomicLossProbabilityComputeForm").valid()) {
                            var val = $("#correctedExpectation").val();
                            var rowsData = $("#fxEconomyLossProbabilityComputeGrid").datagrid('getData').rows;
                            for (let i = 0; i < rowsData.length; i++) {
                                rowsData[i].correctedExpectation = val;
                                $.ajax({
                                    url: getFxEconomyLossProbabilityComputeController(),
                                    contentType: "application/json",
                                    data: JSON.stringify(rowsData[i]),
                                    type: "put",
                                    success: function (data) {
                                        (i == rowsData.length - 1) && (createFxEconomyLossProbabilityComputeGrid(), slidebar.close(), Util.alert(data.message));
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
    };
    var assistProbabilityCompute = function (field) {
        var cProbability = $("#correctedProbability").parent().parent().parent(),
            cExpectation = $("#correctedExpectation").parent().parent().parent();
        if (field == "correctedProbability") {
            cProbability.show();
            cExpectation.hide();
        } else if (field == "correctedExpectation") {
            cProbability.hide();
            cExpectation.show();
        }
    };

    var deleteFxEconomyLossProbabilityCompute = function () {
        var rows = $("#fxEconomyLossProbabilityComputeGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxEconomyLossProbabilityComputeController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxEconomyLossProbabilityComputeGrid();
                }
            });
        }, function () {
            return;
        });

    };

    var taskIsFinish = function (obj) {
        for (var _key in obj) if (!obj[_key]) return false;
        return true;
    };


    var exportFxEconomyLossProbabilityComputeTemplet = function () {
        window.location.href = getServer() + "/excel/经济损失风险评估-概率性损失区划模板.xlsx";
    }
    var exportFxEconomyLossProbabilityCompute = function () {
        let province = $("#provinceSelect").val(), city = $("#citySelect").val(), area = $("#areaSelect").val();
        window.location.href = getFxEconomyLossProbabilityComputeController() + "/export?province=" + province + "&city=" + city + "&area=" + area;
    };
    var importFxEconomyLossProbabilityCompute = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/经济损失风险评估-概率性损失区划模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxEconomyLossProbabilityComputeController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                }
            });
        });
    };

    return {
        init: init
    };
});
